package cn.com.dashihui.kit;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DoubleField;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class LuceneKit {
	
	/**
	 * 为商品信息建立索引
	 */
	public static void createIndex(){
		IndexWriter writer = null;
		try {
			SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
			Directory index = FSDirectory.open(Paths.get(PropKit.get("constants.lucenePath")));//new RAMDirectory();
			//建立新索引
			IndexWriterConfig config = new IndexWriterConfig(analyzer);
			config.setOpenMode(OpenMode.CREATE);
			writer = new IndexWriter(index, config);
			List<Record> goodsList = Db.find("SELECT g.* FROM v_goods g ORDER BY g.storeid");
			Set<Integer> storeidList = new HashSet<Integer>();
			List<Record> selfGoodsList = new ArrayList<Record>();
			
			//1.将所有非直营的商品生成索引，直营商品挪到另一个集合中
			if(goodsList!=null){
				for(Record goods : goodsList){
					if(goods.getInt("isSelf")==1){
						selfGoodsList.add(goods);
					}else{
						storeidList.add(goods.getInt("storeid"));
						writer.addDocument(buildDocument(goods));
					}
				}
			}
			//2.处理直营商品
			if(selfGoodsList.size()!=0){
				//遍历所有直营商品
				for(Record goods : selfGoodsList){
					//按每个分公司复制一份的方式生成索引，这样，在搜索时就可以解决不能用小括号的问题了
					for(int storeid : storeidList){
						goods.set("storeid", storeid);
						writer.addDocument(buildDocument(goods));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			//异常回滚
			if(writer!=null){
				try {
					writer.rollback();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		} finally {
			//关闭
			if(writer!=null){
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private static Document buildDocument(Record goods){
		Document document = new Document();
		document.add(new StringField("storeid", String.valueOf(goods.getInt("storeid")),Field.Store.YES));
		document.add(new IntField("id", goods.getInt("id"),Field.Store.YES));
		document.add(new TextField("name", goods.getStr("name"),Field.Store.YES));
		if(!StrKit.isBlank(goods.getStr("brandName"))){
			document.add(new TextField("brandName", goods.getStr("brandName"),Field.Store.YES));
		}
		document.add(new StringField("spec", goods.getStr("spec"),Field.Store.YES));
		if(!StrKit.isBlank(goods.getStr("shortInfo"))){
			document.add(new TextField("shortInfo", goods.getStr("shortInfo"),Field.Store.YES));
		}
		document.add(new DoubleField("marketPrice", goods.getDouble("marketPrice"),Field.Store.YES));
		document.add(new DoubleField("sellPrice", goods.getDouble("sellPrice"),Field.Store.YES));
		if(!StrKit.isBlank(goods.getStr("thumb"))){
			document.add(new StringField("thumb", goods.getStr("thumb"),Field.Store.YES));
		}
		document.add(new TextField("categoryonName", goods.getStr("categoryonName"),Field.Store.YES));
		document.add(new TextField("categorytwName", goods.getStr("categorytwName"),Field.Store.YES));
		document.add(new TextField("categorythName", goods.getStr("categorythName"),Field.Store.YES));
		document.add(new TextField("categoryfoName", goods.getStr("categoryfoName"),Field.Store.YES));
		//专门用于数字排序的字段
		document.add(new NumericDocValuesField("sellPriceForSort", goods.getDouble("sellPrice").longValue()));
		document.add(new TextField("isSelf", String.valueOf(goods.getInt("isSelf")),Field.Store.YES));
		return document;
	}
}